#include <stdio.h>
#include "sqlite3.h"

static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
	int i;
	for (i = 0; i < argc; i++) {
		printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
	}
	
	printf("\n");
	
	return 0;
}

int main(int argc, char **argv)
{
	sqlite3 *db;
	char *zErrMsg = 0;
	int rc;
	
	rc = sqlite3_open(argv[1], &db);
	
	if (rc) {
		fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		return 1;
	}
	
	rc = sqlite3_exec(db, "CREATE TABLE 'a' (Id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, StartTime INTEGER NOT NULL UNIQUE, EndTime INTEGER NOT NULL UNIQUE, Value TEXT)", callback, 0, &zErrMsg);
	
	if (rc != SQLITE_OK) {
		fprintf(stderr, "SQL error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
	}
	
	////////////////////////////////////////////////////////////////////////////
	
	rc = sqlite3_exec(db, "INSERT INTO 'a' VALUES (0, 1, 2, 'blah')", callback, 0, &zErrMsg);
	
	if (rc != SQLITE_OK) {
		fprintf(stderr, "SQL error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
	}
	
	sqlite3_stmt *stmt = 0;
	
	if (sqlite3_prepare_v2(db, "INSERT INTO a (StartTime, EndTime, Value) VALUES(?, ?, ?)", -1, &stmt, NULL)) {
		fprintf(stderr, "SQL error: Create query !");
	}
	
	if (sqlite3_bind_int64(stmt, 1, 4) != SQLITE_OK) {
		fprintf(stderr, "SQL error: Bind parameter StartTime !");
	}
	
	if (sqlite3_bind_int64(stmt, 2, 5) != SQLITE_OK) {
		fprintf(stderr, "SQL error: Bind parameter EndTime !");
	}
	
	if (sqlite3_bind_text(stmt, 3, "12IntegerValue 10", -1, SQLITE_STATIC) != SQLITE_OK) {
		fprintf(stderr, "SQL error: Bind parameter Value !");
	}
	
	if (sqlite3_step(stmt) != SQLITE_DONE) {
		fprintf(stderr, "SQL error: Insert data !");
	}
	
	if (sqlite3_finalize(stmt)) {
		fprintf(stderr, "SQL error: Finalize query !");
	}
	
	////////////////////////////////////////////////////////////////////////////
	
	rc = sqlite3_exec(db, "SELECT * FROM 'a'", callback, 0, &zErrMsg);
	
	if (rc != SQLITE_OK) {
		fprintf(stderr, "SQL error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
	}
	
	////////////////////////////////////////////////////////////////////////////
	
	if (sqlite3_prepare_v2(db, "SELECT Value FROM a WHERE EndTime = 5", -1, &stmt, NULL)) {
		fprintf(stderr, "SQL error: Create query !");
	}
	
	if (sqlite3_step(stmt) != SQLITE_ROW) {
		fprintf(stderr, "SQL error: Select data !");
	}
	
	printf("Value = %s\n", sqlite3_column_text(stmt, 0));
	
	if (sqlite3_finalize(stmt)) {
		fprintf(stderr, "SQL error: Finalize query !");
	}

	sqlite3_close(db);
	
	return 0;
}
